import type { RouteRecordType } from './index'

const hasPermission = (role: string, route: RouteRecordType) => {
  if (route.meta?.roles) {
    return route.meta.roles.includes(role)
  }
  return true
}

export const filterAsyncRoutes = (routes: RouteRecordType[], role: string) => {
  const res: RouteRecordType[] = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(role, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, role)
      }
      res.push(tmp)
    }
  })

  return res
}
